import { t } from 'i18next'
import { fetchDeleteVideo, fetchPauseResumeVideo, fetchStopVideo, fetchStartVideo } from '@/api/manager/mccMtVideo'
import { FetchGetAllVideoReturnProps, FetchStartVideoParamsProps } from '@/api/manager/mccMtVideo/interface'
import Alert, { Confirm } from '@/components/Alert'
import { formatSeconds } from '@/utils/format'
import { ColumnProps, Tag } from '@kedacom/react-next'
import { ValueType } from '@kedacom/react-next/dist/types/utils'
import { useEffect, useState } from 'react'
import shallow from 'zustand/shallow'
import { useMccStore } from '../../store'
import { VideoModalType, useMccMtVideoStore } from './store'
import { EditBtnIcon, ReadBtnIcon } from './style'

const useHookData = () => {
	const columns: ColumnProps<FetchGetAllVideoReturnProps>[] = [
		{
			title: t('录像文件名'),
			dataKey: 'rec_file',
			width: 100,
			render: (rowData, value, index) => {
				var text = value
				if (value && value.lastIndexOf('.') !== -1) {
					text = value.substring(0, value.lastIndexOf('.'))
				}
				return (
					<div className="title ellipsis" title={text}>
						{text}
					</div>
				)
			},
		},
		{
			title: t('录像时长'),
			dataKey: 'duration',
			width: 70,
			render: (rowData, value, index) => {
				var text = value || '0'
				text = formatSeconds(text)
				return <div>{text}</div>
			},
		},
		{
			title: t('录像状态'),
			dataKey: 'state',
			width: 70,
			render: (rowData, value, index) => {
				let text =
					value === 1 ? t('录像中') : value === 2 ? t('已暂停') : value === 0 ? t('已停止') : t('未录像')
				return <span className={`state ${value === 2 ? 'red' : 'normal'}`}>{text}</span>
			},
		},
		{
			title: t('操作'),
			dataKey: 'action',
			width: 50,
			render: (rowData: FetchGetAllVideoReturnProps, value: any, index: number, isSelected: boolean) => {
				return rowData.state === 2 || rowData.state === 1 ? (
					// 已暂停的和录像中 的不可以编辑 只读
					<Tag onClick={(e) => toEditOrRead(rowData, isSelected, e, 'detail')}>
						<ReadBtnIcon className="read-btn-icon"></ReadBtnIcon>
					</Tag>
				) : (
					<Tag onClick={(e) => toEditOrRead(rowData, isSelected, e, 'update')}>
						<EditBtnIcon className="edit-btn-icon"></EditBtnIcon>
					</Tag>
				)
			},
		},
	]
	const {
		selectedRows,
		selectedRowIds,
		setSelectedRows,
		setSelectedRowIds,
		getAllVideo,
		allVideo,
		modalInfo,
		setModalInfo,
		reload,
	} = useMccMtVideoStore(
		(state) => ({
			vrsServerList: state.vrsServerList,
			getAllVideo: state.getAllVideo,
			allVideo: state.allVideo,
			modalInfo: state.modalInfo,
			setModalInfo: state.setModalInfo,
			setSelectedRows: state.setSelectedRows,
			setSelectedRowIds: state.setSelectedRowIds,
			selectedRows: state.selectedRows,
			selectedRowIds: state.selectedRowIds,
			reload: state.reload,
		}),
		shallow
	)
	
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)

	useEffect(() => {
		getAllVideo()
	}, [])

	useEffect(() => {
		let idLists: string[] = []
		selectedRows.forEach((item: FetchGetAllVideoReturnProps) => {
			idLists.push(item.id)
		})
		setSelectedRowIds(idLists)
	}, [selectedRows])

	const toEditOrRead = (
		record: FetchGetAllVideoReturnProps,
		isSelected: boolean,
		e: React.MouseEvent<Element, MouseEvent>,
		type: VideoModalType
	) => {
		if (isSelected) {
			e.stopPropagation()
		}
		let text = record.rec_file
		if (record.rec_file && record.rec_file.lastIndexOf('.') !== -1) {
			text = record.rec_file.substring(0, record.rec_file.lastIndexOf('.'))
		}
		setModalInfo({
			isShow: true,
			type: type,
			videos: [record],
			modalBack: {
				vrs_id: record.vrs_id,
				vrs_name: record.vrs_name,
				rec_file: text,
				publish_mode: record.publish_mode,
			},
		})
	}
	/**开始按钮 */
	const startVideo = () => {
		let _selectedRows =
			allVideo?.filter((item) => {
				return selectedRowIds.includes(item.id)
			}) || []
		if (!_selectedRows.length) {
			Alert(t('请选择至少一条终端录像'))
			return
		}
		/**去掉 暂停状态后的勾选项 */
		let videoVOsStart = _selectedRows.filter((item) => {
			return item.state === 5
		})
		/**暂停状态的的勾选项 */
		let pauseDataRecId: string[] = []
		_selectedRows.forEach((item) => {
			if (item.state === 2) {
				pauseDataRecId.push(item.rec_id)
			}
		})
		let paramsStart: FetchStartVideoParamsProps = {
			meeting_id: meetingMoid,
			mt_videos: videoVOsStart || [],
		}
		let paramPause = {
			meeting_id: meetingMoid,
			rec_ids: pauseDataRecId || [],
			state: 2,
		}
		if (videoVOsStart.length) {
			fetchStartVideo(paramsStart).then((res) => {
				if (!res.success) {
					Alert(res.description || '')
				}
			})
		}
		if (pauseDataRecId.length) {
			fetchPauseResumeVideo(paramPause).then((res) => {
				if (!res.success) {
					Alert(res.description || '')
				}
			})
		}
	}
	/**暂停按钮 */
	const pauseVideo = () => {
		let _selectedRows =
			allVideo?.filter((item) => {
				return selectedRowIds.includes(item.id)
			}) || []
		if (!_selectedRows.length) {
			Alert(t('请选择至少一条终端录像'))
			return
		}
		/**进行中状态的的勾选项 */
		let recId: string[] = []
		_selectedRows.forEach((item) => {
			if (item.state === 1) {
				recId.push(item.rec_id)
			}
		})
		if (recId.length) {
			let param = {
				meeting_id: meetingMoid,
				rec_ids: recId || [],
				state: 1,
			}
			fetchPauseResumeVideo(param).then((res) => {
				if (!res.success) {
					Alert(res.description || '')
				}
			})
		}
	}
	/**
	 *结束按钮
	 * @param isEndAll 是否结束全部录像
	 * @returns
	 */
	const stopVideo = (isEndAll: boolean) => {
		let title = isEndAll ? t('确定结束全部终端录像？') : t('确定结束所选终端录像？')
		let _selectedRows =
			allVideo?.filter((item) => {
				return selectedRowIds.includes(item.id)
			}) || []
		if (!isEndAll) {
			if (!_selectedRows.length) {
				Alert(t('请选择至少一条终端录像'))
				return
			}
		}
		var recIds: string[] = []
		var notStartRecIds: string[] = []
		let list = isEndAll ? allVideo : _selectedRows
		list?.forEach((item) => {
			if (item.state === 1 || item.state === 2) {
				recIds.push(item.rec_id)
			} else {
				notStartRecIds.push(item.id)
			}
		})
		if (recIds.length === 0 && notStartRecIds.length === 0) {
			return false
		}
		Confirm(title, () => {
			if (recIds.length !== 0) {
				let param = {
					meeting_id: meetingMoid,
					rec_ids: recIds || [],
				}
				fetchStopVideo(param).then((res) => {
					if (!res.success) {
						Alert(res.description || '')
					} else {
						reload()
					}
				})
			}
			if (notStartRecIds.length !== 0) {
				let param = {
					meeting_id: meetingMoid,
					rec_ids: notStartRecIds || [],
				}
				fetchDeleteVideo(param).then((res) => {
					if (!res.success) {
						Alert(res.description || '')
					} else {
						reload()
					}
				})
			}
		})
	}
	const onRowSelect = (e: React.MouseEvent, rowData: any, id: string, nextSelected: boolean, index: number) => {
		e.stopPropagation()
		let rowIdField = 'id'
		if (!nextSelected) {
			const filter = selectedRows.filter((item: any) => item[rowIdField] !== rowData[rowIdField], [])
			setSelectedRows(filter)
		} else {
			let newTemp = rowData
			let arr = [...selectedRows, newTemp]
			setSelectedRows(arr)
		}
	}
	const onRowSelectAll = (
		e: any,
		selectedRowData: FetchGetAllVideoReturnProps[],
		selectedRowIds: ValueType[],
		nextSelected: boolean
	) => {
		if (!nextSelected) {
			setSelectedRows([])
		} else {
			setSelectedRows(selectedRowData)
		}
	}
	const onRowClick = (e: any, rowData: FetchGetAllVideoReturnProps, id: any, selected: any, index: any) => {
		let isMoreSelected = selectedRows.length > 1
		if (isMoreSelected) {
			setSelectedRows([rowData])
		} else {
			selected ? setSelectedRows([rowData]) : setSelectedRows([])
		}
	}
	return {
		columns,
		tableData: allVideo,
		onRowSelect,
		onRowSelectAll,
		onRowClick,
		selectedRows,
		selectedRowIds,
		reload,
		startVideo,
		pauseVideo,
		stopVideo,
		modalInfo,
		setModalInfo,
	}
}
export default useHookData
